//
//  EmojiPictureView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/5/21.
//

import SwiftUI
import Kingfisher

//表情包
struct EmojiPictureView: View {
    @StateObject var viewModel = EmojiPictureViewModel()
    @State private var showPicker = false //选择图片选择框
    @State var maxItems = 1
    @State private var showDelDialog = false //删除
    @State private var delIndex = -1
    
    var body: some View {
        ZStack{
            GeometryReader { geometry in
                let spacing: CGFloat = 10 // 行间距和列间距
                let columns = Array(repeating: GridItem(.flexible(), spacing: spacing), count: 5) // 列间距
                // 计算单元格宽度（总宽度减去列间距）
                let itemWidth = (geometry.size.width - spacing * 4) / 5
                ScrollView {
                    LazyVGrid(columns: columns, spacing: 10) {
                        ForEach(Array(viewModel.tableItem.enumerated()), id: \.element.objectId) { index, item in
                            switch item.objectId ?? "" {
                            case "add":
                                ZStack {
                                    // 圆角虚线正方形
                                    RoundedRectangle(cornerRadius: 10)
                                        .strokeBorder(style: StrokeStyle(lineWidth: 2, dash: [5, 3]))
                                        .frame(width: itemWidth, height: itemWidth) // 保证宽高相等
                                        .foregroundColor(.black)
                                    
                                    Image(.appIconAddEmpty)
                                        .resizable()
                                        .scaledToFit()
                                        .padding(10)
                                        .frame(width: itemWidth, height: itemWidth)
                                        .clipShape(RoundedRectangle(cornerRadius: 5))
                                }.contentShape(Rectangle())
                                    .onTapGesture {
                                        showPicker.toggle()
                                    }
                            default:
                                if let fileUrlPath = ImageFileManager.loadImagePath(item.path ?? "") {
                                    KFImage(URL(fileURLWithPath: fileUrlPath))
                                        .resizable()
                                        .setProcessor(DownsamplingImageProcessor(size: CGSize(width: itemWidth * 5, height: itemWidth * 5)))
                                        .placeholder{
                                            Image(.appDefaultLogo)
                                                .resizable()
                                                .scaledToFill()
                                                .padding(.horizontal,itemWidth / 4)
                                                .padding(.vertical,itemWidth / 4)
                                        }
                                        .fade(duration: 0.1)
                                        .diskCacheExpiration(.days(7)) // 设置磁盘缓存过期时间
                                        .aspectRatio(contentMode: .fit)
                                        .frame(width: itemWidth, height: itemWidth) // 保证宽高相等
                                        .contentShape(Rectangle())
                                        .onTapGesture {
                                            NotificationCenter.default.post(name: .emojiPicture, object: item)
                                        }
                                        .contextMenu {
                                            Button("删除", role: .destructive) {
                                                showDelDialog = true
                                                delIndex = index
                                            }
                                            Button("编辑") {
                                                if let uiImage = ImageFileManager.loadImage(item.path ?? "") {
                                                    showEditDialog(title: "编辑信息",hint: "请输入表情包信息", content: item.text ?? "", uiImage: uiImage) { it in
                                                        if !it.isEmpty {
                                                            item.text = it
                                                            viewModel.doSave(bean: item)
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        .alert("温馨提示",isPresented:$showDelDialog) {
                                            Button("取消",role: .cancel){}
                                            Button("确定删除",role: .destructive) {
                                                viewModel.doDel(index: delIndex)
                                            }
                                        }
                                }
                                
                            }
                        }
                        
                    }
                }
            }
        }
        .padding(10)
        .onAppear{
            if !viewModel.isInit{
                viewModel.getData()
                viewModel.isInit = true
            }
        }.sheet(isPresented: $showPicker) {
            MediaPicker(
                selectionLimit: $maxItems,
                maxFileSizeMB: 100, // 100MB
                filterType: MediaFilterType.images,
                isPresented: $showPicker,
                onComplete: { items in
                    showPicker = false
                    switch items.first?.type {
                    case .localImage(let uiImage):
                        //添加为表情包
                        showEditDialog(title: "描述信息",hint: "请输入表情包信息", content: "", uiImage: uiImage) { it in
                            if !it.isEmpty {
                                viewModel.doAdd(image: uiImage, text: it)
                            }
                        }
                    case .networkImage(_, _, _):
                        break
                    case .localImagePath(_):
                        break
                    case .localVideo(_):
                        break
                    case .none:
                        break
                    }
                }
            )
        }
    }
}

#Preview {
    EmojiPictureView()
}
